package com.xdf.wxbebarrel.utils;


import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @ClassName:JacksonDateDeserializer
 * @Description:TODO
 * @Author:chanchaw
 * @Date:2020-01-09 10:05
 * @Version:1.0
 **/
public class JacksonDateDeserializer extends JsonDeserializer<Date> {
    @Override
    public Date deserialize(JsonParser jp, DeserializationContext deserializationContext) throws IOException, JsonProcessingException {
        String date = jp.getText();
        int index = date.indexOf("T");
        SimpleDateFormat format = null;
        if (index >= 0)
            format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
        else
            format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        try {
            Date feDate = format.parse(date);// 根据前端传递来的日期的格式创建日期对象
            return new Date(feDate.getTime());
        } catch (ParseException e) {
            throw new BusinessException("自定义反序列化日期类型时出现异常");
        }
    }
}